<template>
  <el-dialog
    v-model="dialogVisible"
    title="新增用户"
    width="60%"
    center
    @close="closeDialog(false)"
  >
    <el-form
      :rules="rules"
      :model="form"
      label-width="100px"
      ref="validateForm"
    >
      <el-form-item label="用户名" prop="user_name">
        <el-input v-model="form.user_name" />
      </el-form-item>
      <el-form-item label="用户密码" prop="user_password">
        <el-input v-model="form.user_password" />
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <!-- 这里不要使用默认的,默认的close不是响应式的 -->
        <el-button
          @click="
            () => {
              closeDialog(false)
            }
          "
        >
          取消
        </el-button>
        <el-button type="primary" @click="submit(data)">确认</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script>
import { defineComponent, reactive, toRefs, ref, computed } from 'vue'
import { Plus } from '@element-plus/icons-vue'

import axios from 'axios'

//
export default {
  props: {
    dialogVisible: Boolean,
  },
  emits: ['onCloseDialog'],
  setup(props, { emit }) {
    const validateForm = ref()
    const state = reactive({
      dialogVisible: props.dialogVisible,
      form: {
        user_name: '',
        user_password: '',
      },
    })

    const closeDialog = (visible) => {
      // 使用父组件的方法,方法名,传递的参数
      emit('onCloseDialog', visible)
    }
    // 校验规则
    const rules = {
      user_name: [
        { required: true, message: '用户名不能为空', trigger: 'blur' },
      ],
      user_password: [
        { required: true, message: '用户密码不能为空', trigger: 'blur' },
      ],
    }
    // 统一管理添加的方法
    const submit = () => {
      //验证表单的值都填完没有
      validateForm.value.validate((valid) => {
        //console.log(valid) //如果有没填的就是false,都填了就是true
        //获取表单数据

        if (valid) {
          const obj = {
            user_name: state.form.user_name,
            user_password: state.form.user_password,
          }
          axios.post('/blog', obj).then((res) => {
            console.log(res)
            // 提交后重置/清空表单
            validateForm.value.resetFields()
            // 关闭表单
            emit('onCloseDialog', false, res.data)
          })
        }
      })
    }
    return {
      ...toRefs(state),
      closeDialog,
      rules,
      submit,
      validateForm,
    }
  },
}
</script>

<style></style>
